package com.wunu.smartlock1;


import android.Manifest;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.clj.fastble.data.BleDevice;
import com.wunu.smartlock1.activity.AuthorizedLockActivity;
import com.wunu.smartlock1.activity.LockRecordActivity;
import com.wunu.smartlock1.activity.QrcodeActivity;
import com.wunu.smartlock1.activity.ScanListActivity;
import com.wunu.smartlock1.activity.TemporyLockActivity;
import com.wunu.smartlock1.bluetooth.WunuBlueManager;
import com.wunu.smartlock1.bluetooth.command.OpenLockSetp2Command;
import com.wunu.smartlock1.bluetooth.command.OpenLockStep1Command;
import com.wunu.smartlock1.net.NetComponent;
import com.wunu.smartlock1.net.api.LockEventApi;
import com.wunu.smartlock1.net.api.LockManageApi;
import com.wunu.smartlock1.net.response.ApiNormalResponse;
import com.wunu.smartlock1.net.response.ApiSimpleResponse;
import com.wunu.smartlock1.net.response.BaseCodeInfo;
import com.wunu.smartlock1.net.response.LockEvent;
import com.wunu.smartlock1.net.response.LockItem;
import com.wunu.smartlock1.util.BlueUtil;
import com.wunu.smartlock1.util.CommonUtil;
import com.wunu.smartlock1.xxtea.XXTEA;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import retrofit2.Call;

public class MainActivity_allOk extends AppCompatActivity implements OnClickListener{
    LockEventApi service = NetComponent.getRetrofit().create(LockEventApi.class);
    String toast;
    private ViewPager viewPager;
    private LinearLayout ll_item;//灰点所在的线性布局
    private ImageView blue_iv;//小蓝点
    int position;//当前界面数（从0开始）
    private int pointWidth;//小灰点的距离
    private List<View> contentList = new ArrayList<View>();

    private static final int HANDLE_HD_EVENT = 992;
    private static final int HANDLE_SCAN_DEVICES_EVENT = 154;
    private static final int HANDLE_PUSH_LOCK_RESULT = 100;
    //
    View inflate;
    Dialog dialog;
    Intent intent = new Intent();

    TextView cancelView;//取消
    TextView resetView;//重置秘钥
    TextView stopView;//停用蓝牙解锁
    TextView deleteView;//删除门锁
    private ProgressDialog pd;
    Context context = this;

    //全局图标控制
    RelativeLayout staticRelativeLayoutNo;
    RelativeLayout staticRelativeLayoutYes;
    int staticOpenId = 0;
    public boolean isPatch(String mac){
        if(BlueUtil.devices==null || BlueUtil.devices.size()<1||mac.length()<5) return false;
        String n2 = mac.substring(mac.length() -5).replaceAll("\\W+","");
        String n1 = null;
        for(int i=0;i<BlueUtil.devices.size();i++){
            n1 = BlueUtil.devices.get(i).getMac().substring(BlueUtil.devices.get(i).getMac().length()-5).replaceAll("\\W+","");
            System.out.println("n1:"+n1+"\tn2:"+n2);
            if(n1.equalsIgnoreCase(n2))return true;
        }
        return false;
    }
    public BleDevice getBleDevice(String mac){
        String n2 = mac.substring(mac.length() -5).replaceAll("\\W+","");
        String n1 = null;
        for(int i=0;i<BlueUtil.devices.size();i++){
            n1 = BlueUtil.devices.get(i).getMac().substring(BlueUtil.devices.get(i).getMac().length()-5).replaceAll("\\W+","");
            System.out.println("n1:"+n1+"\tn2:"+n2);
            if(n1.equalsIgnoreCase(n2))return BlueUtil.devices.get(i);
        }
        return null;
    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLE_HD_EVENT:
                    pd.dismiss();
                    Map<String, Object> stringMap = (Map<String, Object>) msg.obj;
                    System.out.println("开锁返回结果: "+stringMap);
                    final boolean flag ;
                    if (stringMap.get("errMsg") != null || !"1".equals(stringMap.get("success").toString())) {
                        flag = false;
                        Toast.makeText(context, "开锁失败!", Toast.LENGTH_SHORT).show();
                    } else{
                        if(staticRelativeLayoutYes != null)staticRelativeLayoutYes.setVisibility(View.VISIBLE);
                        if(staticRelativeLayoutNo != null)staticRelativeLayoutNo.setVisibility(View.GONE);
                        flag = true;
                        Toast.makeText(context, "开锁成功", Toast.LENGTH_SHORT).show();
                    }
                    //上传开锁结果
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            try{
                                LockEventApi service = NetComponent.getRetrofit().create(LockEventApi.class);
                                int event = flag?LockEvent.EVENT_SUCCESS:LockEvent.EVENT_FAILED;
                                System.out.println("event:"+event);
                                Call<ApiSimpleResponse> call = service.sendOpenLockResult(staticOpenId, flag?LockEvent.EVENT_SUCCESS:LockEvent.EVENT_FAILED);
                                ApiSimpleResponse resp = call.execute().body();
                                System.out.println(staticOpenId+" resp: "+resp);
                                // 发送消息，把服务器返回的本文弹出吐司显示
                                Message msg = handler.obtainMessage();
                                msg.what = HANDLE_PUSH_LOCK_RESULT;
                                msg.obj = resp.getData().getCode();
                                handler.sendMessage(msg);
                            } catch (Exception e) {
                                System.out.println("上传开锁结果异常:" + e);
                            }
                        }
                    }.start();
                break;
                case HANDLE_SCAN_DEVICES_EVENT:
                    handleScanDevicesEvent(msg);
                    break;
                case HANDLE_PUSH_LOCK_RESULT:
                    System.out.println("上传开锁结果 : "+msg);
                    if(200 == (int)msg.obj){
                        Toast.makeText(context, "上传开锁结果成功", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(context, "上传开锁结果失败!", Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    };
    private void handleScanDevicesEvent(Message msg) {
        System.out.println("obj->"+msg.getData());
        if (msg == null || msg.obj == null){
            Toast.makeText(MainActivity_allOk.this, toast+"未获取到用户锁列表", Toast.LENGTH_SHORT).show();
        }
        final List<LockItem> list = (List<LockItem>)msg.obj;
        System.out.println("list size : "+list.size());
        Toast.makeText(MainActivity_allOk.this,"正在搜索附近蓝牙",Toast.LENGTH_SHORT).show();

        System.out.println("搜索到蓝牙个数:"+BlueUtil.devices.size());
        //添加页面
        for (int i=0;i<list.size();i++){
            final LockItem lockItem = list.get(i);
            final View temp ;
            if(isPatch(list.get(i).getMac())){
                temp = LayoutInflater.from(context).inflate(R.layout.smartlock_lock_list_unlock, null);
            }else{
                temp = LayoutInflater.from(context).inflate(R.layout.smartlock_lock_list, null);
            }

            TextView name = temp.findViewById(R.id.lockNameTextView);
            name.setText(list.get(i).getName());
            TextView mac = temp.findViewById(R.id.lockMacTextView);
            mac.setText("MAC："+list.get(i).getMac());


            if(isPatch(list.get(i).getMac())){
                ImageView hitUnlock = temp.findViewById(R.id.hitUnlock);//解锁图标
                final BleDevice thisDevice = getBleDevice(list.get(i).getMac());
                final int openId = list.get(i).getId();
                hitUnlock.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        staticRelativeLayoutNo = temp.findViewById(R.id.lockedIcon);
                        staticRelativeLayoutYes = temp.findViewById(R.id.onLockedIcon);
                        staticOpenId = openId;
                        pd= ProgressDialog.show(MainActivity_allOk.this, "请等待", "正在开锁");
                        //开线程加载数据

                        new Thread() {
                            @Override
                            public void run() {
                                int baseCode = 0;
                                super.run();

                                LockManageApi service = NetComponent.getRetrofit().create(LockManageApi.class);
                                Call<ApiNormalResponse<BaseCodeInfo>> call = service.getLockBaseCode(openId);
                                try{
                                    ApiNormalResponse<BaseCodeInfo> resp = call.execute().body();
                                    baseCode = resp.getData().getData().getBaseCode();
                                }catch (Exception e){System.out.println("获取basecode失败!"+e.getMessage());
                                }

                                System.out.println("---------------open lock step 1----------->blcmd begin basecode:"+baseCode+" openId: "+openId);
                                int[] v = {0, (int)(Math.random() * 10000000)};
                                int[] k = {0,0,0,baseCode};

                                final OpenLockStep1Command o1cmd = new OpenLockStep1Command(XXTEA.encrypt(v,k));
                                final WunuBlueManager manager = WunuBlueManager.Companion.getShared();
                                final int finalBaseCode = baseCode;
                                manager.execute(o1cmd, thisDevice, new Function1<Map<String, ? extends Object>, Unit>() {
                                    @Override
                                    public Unit invoke(Map<String, ?> stringMap) {
                                        if (stringMap.isEmpty()) {
                                            return null;
                                        }
                                        if (stringMap.get("errMsg") != null) {
                                            Message msg = handler.obtainMessage();
                                            msg.what = HANDLE_HD_EVENT;
                                            msg.obj = stringMap;
                                            handler.sendMessage(msg);
                                            return null;
                                        }
                                        int sn = stringMap.get("n") == null ? 0 : Integer.parseInt(stringMap.get("n").toString());
                                        int sA = CommonUtil.getPrePrime(finalBaseCode,sn);
                                        int sB = CommonUtil.getSufPrime(finalBaseCode,sn);
                                        int[] sv = {0, sB};
                                        int[] sk = {0,0,0, sA};
                                        System.out.println("---------------open lock step 2----------->blcmd begin");
                                        OpenLockSetp2Command o2cmd = new OpenLockSetp2Command(XXTEA.encrypt(sv,sk));
                                        manager.execute(o2cmd, thisDevice, new Function1<Map<String, ? extends Object>, Unit>() {
                                            @Override
                                            public Unit invoke(Map<String, ?> stringMap) {
                                                if (stringMap.isEmpty()) {
                                                    return null;
                                                }
                                                Message msg = handler.obtainMessage();
                                                msg.what = HANDLE_HD_EVENT;
                                                msg.obj = stringMap;
                                                handler.sendMessage(msg);
                                                return null;
                                            }
                                        });
                                        return null;
                                    }
                                });
                            }
                        }.start();
                    }
                });
            }


            ImageView a_addButton = temp.findViewById(R.id.addButton);//添加新锁
            ImageView a_memberButton = temp.findViewById(R.id.memberButton);//家庭成员
            ImageView a_temporaryKeyButton = temp.findViewById(R.id.temporaryKeyButton);//临时秘钥
            ImageView a_authorizedButton = temp.findViewById(R.id.authorizedButton);//授权成员
            ImageView a_lockEventButton = temp.findViewById(R.id.lockEventButton);//开锁记录
            ImageView a_lockQRCodeButton = temp.findViewById(R.id.lockQRCodeButton);//锁二维码
            a_addButton.setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {
                    System.out.println("添加新锁");
                    Log.v("添加新锁", "list 1:" );
                    startActivity(intent.setClass(MainActivity_allOk.this, ScanListActivity.class));
                }
            });
            a_memberButton.setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {
                    Log.v("家庭成员", "list 1:" );
                    memberShow();
                }
            });
            a_temporaryKeyButton.setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {
                    Log.v("临时秘钥", "list 1:" );
                    startActivity(intent.setClass(MainActivity_allOk.this, TemporyLockActivity.class));
                }
            });
            a_authorizedButton.setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {
                    Log.v("授权成员", "list 1:" );
                    startActivity(intent.setClass(MainActivity_allOk.this, AuthorizedLockActivity.class));
                }
            });
            a_lockEventButton.setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {
                    Log.v("开锁记录", "list 1:" );
                    startActivity(intent.setClass(MainActivity_allOk.this, LockRecordActivity.class));
                }
            });
            a_lockQRCodeButton.setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {
                    Log.v("锁二维码", "list 1:" );
                    startActivity(intent.setClass(MainActivity_allOk.this, QrcodeActivity.class));
                }
            });

            contentList.add(temp);
        }

        //将图片的引用转化为图片控件存在List的集合中
        for(int i=0;i<contentList.size();i++){
            //绘制小灰点儿，有几个界面就绘制几个
            ImageView points = new ImageView(context);
            points.setImageResource(R.drawable.grey_point);//通过shape文件绘制好灰点
            //给第一个以外的小灰点儿设置左边距，保证三个灰点水平居中
            LinearLayout.LayoutParams lllp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);//拿到灰点所处的线性布局一样的形状（一些距离属性）
            if(i>0)
                lllp.leftMargin = 30;//设置左外边距，像素
            points.setLayoutParams(lllp);//把设置好左外边距的形状设置给灰点
            ll_item.addView(points);//将灰点加入线性布局
        }
        //为了完成蓝点在界面滑动时的动画效果，必须获取到灰点的边距，通过动态的给蓝点设置边距来完成动画效果
        //由于在执行onCreate方法时，界面还没有绘制完成，无法获取pointWidth，设定小蓝点绘制完成的事件监听，当小蓝点绘制完成再获取
        blue_iv.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                //获取小灰点圆心间的距离，第1个灰点和第二个灰点的距离
                pointWidth = ll_item.getChildAt(1).getLeft()-ll_item.getChildAt(0).getLeft();
            }
        });

        VPAdapter vpAdapter = new VPAdapter();//创建适配器
        viewPager.setAdapter(vpAdapter);//ViewPager加载适配器
        //为ViewPager设定监听器，界面是滑动时让蓝点也跟着动
        viewPager.addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            //当前选中第几个界面
            public void onPageSelected(int arg0) {
                position = arg0;
            }
            /**
             * 界面滑动时回调此方法
             * arg0:当前界面数
             * arg1:界面滑动过的百分数（0.0-1.0）
             * arg2:当前界面偏移的像素位置
             */
            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                int width;//小蓝点当前滑动距离
                width = (int) (arg1*pointWidth+arg0*pointWidth);//1个界面就要一个小灰点的距离，再加上滑动过的百分比距离就是当前蓝点的位置
                LayoutParams rllp= (LayoutParams) blue_iv.getLayoutParams();//拿到蓝点所在布局的形状
                rllp.leftMargin=width;//设置蓝点的左外边距
                blue_iv.setLayoutParams(rllp);//将设置好的形状设置给蓝点
            }
            //状态改变时调用：arg0=0还没滑动,arg0=1正在滑动,arg0=2滑动完毕
            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });

        pd.dismiss();
        Toast.makeText(MainActivity_allOk.this, "加载页面成功!", Toast.LENGTH_SHORT).show();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//设置App不显示菜单，黑乎乎的不好看
        //注意这两句代码的顺序，上面一句写在下面一句后面会报错
        setContentView(R.layout.smartlock_activity_main);

        //构建一个下载进度条
        pd= ProgressDialog.show(MainActivity_allOk.this, "请等待", "正在扫描附近蓝牙设备…");

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        ll_item = (LinearLayout) findViewById(R.id.ll_item);
        blue_iv = (ImageView) findViewById(R.id.blue_iv);


        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN},1000);
            } else {
                System.out.println("蓝牙设备校验通过");
                new Thread(){
                    public void run(){
                        BlueUtil.startScan();
                    }
                }.start();

            }
        }

        pd.dismiss();
        //构建一个下载进度条
        pd= ProgressDialog.show(MainActivity_allOk.this, "请等待", "正在查询绑定的锁列表…");

        //开线程加载数据
        new Thread() {
            @Override
            public void run() {
                super.run();
                try{
                    try {
                        Thread.sleep(BlueUtil.ScanTimes - 2);
                    }catch (Exception e){}
                    LockManageApi service = NetComponent.getRetrofit().create(LockManageApi.class);
                    Call<ApiNormalResponse<List<LockItem>>> call = service.getLockList();
                    ApiNormalResponse<List<LockItem>> resp = call.execute().body();
                    System.out.println("resp: "+resp);
                    // 发送消息，把服务器返回的本文弹出吐司显示
                    Message msg = handler.obtainMessage();
                    msg.what = HANDLE_SCAN_DEVICES_EVENT;
                    msg.obj = resp.getData().getData();
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    System.out.println("获取用户锁列表异常:" + e);
                }
            }
        }.start();
    }

    class VPAdapter extends PagerAdapter{
        //返回ViewPager中总页数
        @Override
        public int getCount() {
            return contentList.size();
        }
        //判断视图是否由对象生成
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view==object;
        }
        @Override
        /**
         * 返回将哪一个对象放在当前ViewPager中
         * container：每一页的父容器
         * position：当前页（从0开始）
         */
        public Object instantiateItem(ViewGroup container, int position) {
            //浪费资源，每次滑到新的页都会创建新的的ImageView，我们选择先把ImageView控件存在List集合中，再按需要获取
            View content = contentList.get(position);
            container.addView(content);
            return content;
        }
        @Override
        /**
         * 从ViewPager中移除View对象
         */
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }


    public void memberShow(){
        dialog = new Dialog(this,R.style.smartlock_ActionSheetDialogStyle);
        inflate = LayoutInflater.from(this).inflate(R.layout.smartlock_buttom_dialog, null);
        cancelView = inflate.findViewById(R.id.cancel);//取消弹框
        resetView = inflate.findViewById(R.id.resetlock);//取消弹框
        deleteView = inflate.findViewById(R.id.deletelock);//取消弹框
        stopView = inflate.findViewById(R.id.stoplock);//取消弹框
        resetView.setOnClickListener(this);
        cancelView.setOnClickListener(this);
        deleteView.setOnClickListener(this);
        stopView.setOnClickListener(this);
        dialog.setContentView(inflate);
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity( Gravity.BOTTOM);
        dialog.show();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if(id == R.id.cancel){
            dialog.dismiss();
        }else if(id == R.id.resetlock){
            Toast.makeText(this,"点击了重置秘钥按钮",Toast.LENGTH_SHORT).show();
        }else if(id == R.id.deletelock){
            Toast.makeText(this,"点击了删除门锁按钮",Toast.LENGTH_SHORT).show();
        }else if(id == R.id.stoplock){
            Toast.makeText(this,"点击了停用蓝牙解锁按钮",Toast.LENGTH_SHORT).show();
        }
        //dialog.dismiss();
    }
    /*
    * 拉取锁列表
    * */
    private void fetchLockList() {
        LockManageApi api = NetComponent.getRetrofit().create(LockManageApi.class);
        Call<ApiNormalResponse<List<LockItem>>> call = api.getLockList( );
        try {
            ApiNormalResponse<List<LockItem>> resp = call.execute().body();
            Handler handler = new Handler(){
                @Override
                public void handleMessage(Message msg){
                    List<LockItem> locks = (List<LockItem>)msg.obj;
                    System.out.println("锁列表" + locks);
                    // TODO: - 显示锁列表
                    
                }
            };
            Message msg = handler.obtainMessage();
            if(resp == null || resp.getData() == null)msg.obj = null;
            else msg.obj = resp.getData().getData();
            handler.sendMessage(msg);
        } catch (Exception e) {
            System.out.println("开锁异常" + e);
        }

    }
}
